<template>
	<view :style="skin" class="putStorage">
		<view class="reported">
			<view class="flex_box" v-if="JSON.stringify(BLEObj) != '{}'">
				<view>
					{{$t('lease.productID')}}：{{BLEObj.productId}}
				</view>
				<u-button color="var(--subjectColor)" :disabled="putDisabled" @click="leaStore">

					<text class="btnText">{{$t('property.applyReceiving')}}</text>
				</u-button>
				<!-- 	
				<u-button color="var(--subjectColor)" @click="setStoreNum">
				
					<text class="btnText">申请入库</text>
				</u-button> -->
			</view>
			<view class="flex_box" v-else>
				<u-button color="var(--subjectColor)" @click="isBlueOpne">

					<text class="btnText">{{$t('lease.searchDevice')}}</text>
				</u-button>
			</view>
		</view>

		<view class="record">
			<view class="recordTitle ">
				<view class="productid">{{$t('lease.productID')}}:</view>
				<view class="productModel">{{$t('lease.productModel')}}</view>
				<view class="audio">{{$t('lease.status')}}</view>
			</view>
			<view class="recordList " v-for="(item,index) in storageRecord" :key="index">
				<view class="productid">{{item.productId}}</view>
				<view class="productModel">{{item.productModel}}</view>
				<view class="audio">
					<u-icon v-if="item.stockInAudit == 1" name="checkmark-circle" color="#81B337" size="24"></u-icon>

					<u-loading-icon size="24" v-else-if="item.stockInAudit == 0"></u-loading-icon>

					<text style="color: red;" v-else-if="item.stockInAudit == 2"
						class="iconfont icon-a-mingchengclose-circle-line iconContent"></text>
				</view>

			</view>
		</view>
		
		<u-popup :round="16" :show="show" mode="center">
			<view class="popupBox">
				<view class="title">
					收到多条符合数据
				</view>
				
				<view class="center">
					<view class="textInfo" v-for="(item,index) in checkArr" >
						
						<text :class="checkIndex == index?'checkSucc':''" @click="handleCheckIndex(index)">{{item.productId}}</text>
					</view>
				
				</view>
				<view class="handleBtn">
					<u-button  type="primary" :plain="true" color="var(--borderColor)"
						shape="circle" :hairline="true" @click="btnCancel">
						<text class="cancelText">{{$t('me.Cancel')}}</text>
					</u-button>
					<u-button type="primary" shape="circle" color="var(--subjectColor)" @click="btnConfirm">
						<text class="confirmText">{{$t('me.Confirm')}}</text>
					</u-button>
				</view>
				
			</view>
		</u-popup>

	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		stockIn,
		gtStockInlogs
	} from '@/api/device.js'
	import toast from 'uview-ui/libs/config/props/toast';
	import {
		addDevice,
		getPidInStore
	} from '@/utils/sql/sqlDevice.js'
	import {
		mulDataDevice,
		pidToMAC,
		formatHexString,
		repetitionDataFil,
		addColonEveryTwoChars,
		getNewYMDHMS
	} from '@/utils/index.js'
	import {
		addDeviceType,
		getDevModel
	} from '@/utils/sql/sqlDeviceType.js'
	import {
		adressAuthority
	} from '@/utils/jurisdiction.js'
	export default {
		data() {
			return {
				show:false,
				ble: uni.requireNativePlugin('ble'),
				BLEObj: {
					// productId: '239623940'
				},
				putDisabled: false,
				storageRecord: [],
				time: null,
				tipsTime: null,
				returnData: null,
				checkArr:[],
				checkIndex:-1,
			};
		},
		computed: {
			...mapState({
				skin: state => state.theme.skin
			})

		},
		methods: {
			btnCancel(){
				console.log('关闭');
				this.checkIndex = -1;
				this.checkArr = [];
				this.show = false
			},
			btnConfirm(){
				console.log('确定');
				if(this.checkIndex > -1){
					let checkObj = this.checkArr[this.checkIndex].productId
					this.handleReturn(checkObj) //查找本地数据内容
					this.btnCancel();
				}
				
			},
			handleCheckIndex(index){
				console.log(index);
				this.checkIndex = index
			},
			timePopup() { //时间到了，取消数据监听
				clearTimeout(this.tipsTime)
				let that = this
				this.tipsTime = setTimeout(() => {

					clearInterval(that.time)

					uni.showToast({
						title: that.$t('lease.DeviceNotFound'),
						icon: 'none'
					})
				}, 10000)
			},
			handleReturn(mac) {
				clearTimeout(this.tipsTime);
				clearInterval(this.time)
				uni.hideLoading();
				this.BLEObj = {
					productId: mac
				}

				this.getStockList()

			},
			isBlueOpne() {
				let that = this
				this.ble.isUiThreadOpenGPS(function(res) {
					console.log('接收', res.code); //-1为未开 1为已开
					if (res.code == -1) {
						uni.showToast({
							title: 'Please turn on positioning',
							icon: 'none'
						})
						return
					}

					adressAuthority().then(res => {
						console.log(res);
						// 判断蓝牙是否打开
						uni.openBluetoothAdapter({
							success() {
								that.handleBack();
							},
							fail() {
								uni.showToast({
									title: 'Bluetooth is off',
									icon: 'none'
								})
								return false
							},
						})
					})

				});


			},
			handleBack() {

				// 调试
				// this.handleReturn('239623940')
				// return false
				// this.ble = uni.requireNativePlugin('ble');
				clearInterval(this.time)
				this.ble.init();
				this.ble.start();
				// 搜索设备前，重置mac
				this.ble.resetMac();
				this.returnData = null
				let that = this
				uni.showLoading({
					title: that.$t('lease.Waiting'),
					mask: true
				})
				this.timePopup()
				// 接收数据  群收到消息
				this.time = setInterval(() => {
					console.log('倒计时');
					that.ble.getBackData(function(res) {

						if (res.data.length > 0) {
							console.log(res.data);
							// let orderNum = parseInt(res.data[0].msg.slice(4, 6), 16);
							uni.showToast({
								title: res.data,
								icon: 'none'
							})

							// res.data = [{
							// 		"mac": "00:00:0E:48:5F:04",
							// 		"name": "null",
							// 		"msg": "18fffcffffffffffff6f080084000066517c00007b3275870000000000000"
							// 	},
							// 	{
							// 		"mac": "00:00:0E:48:68:4C",
							// 		"name": "null",
							// 		"msg": "18fffcffffffffffff6f080084000066517c00007b3275870000000000000"
							// 	},
							// 	{
							// 		"mac": "00:00:0E:48:68:4F",
							// 		"name": "null",
							// 		"msg": "18fffcffffffffffff6f080084000066517c00007b3275870000000000000"
							// 	}
							// ]
							let result = repetitionDataFil(res.data, 252)
							console.log(result);
							if (result && that.returnData == null) { //已经有数据上报了，不再处理
								if (result.length == 1) {
									console.log('符合', result[0]);
									that.returnData = result[0]
									let obj = mulDataDevice(result[0].msg) //处理设备返回的信息 7条命令集合
									console.log(obj);
									if (obj.keys == '8871736e867c66' || obj.keys == '6f84667c7b87') { //还灯命令 或者 获取读取设备信息
										let mac = parseInt(result[0].mac.replace(/:/g, ''), 16); //将mac转为十进制
										that.handleReturn(mac) //查找本地数据内容
									}
								}else{
									clearTimeout(that.tipsTime);
									clearInterval(that.time)
									uni.hideLoading();
									result.map(item =>{
										return item.productId = parseInt(item.mac.replace(/:/g, ''), 16); 
									})
									that.checkArr = result
									that.checkIndex = 0
									that.show = true
								}

							}
							that.ble.clearData()
						}
					})

				}, 2000)
			},

			getStockList() {

				gtStockInlogs({
					productId: this.BLEObj.productId
				}).then(res => {
					if (res.code == 0) {
						this.storageRecord = res.data
					} else {
						this.storageRecord = []
					}
					console.log(res);
				})
			},
			async addDeviceDB(data) {
				let Property = JSON.parse(data.productProperty)
				let obj = {
					customerAccount: data.customerAccount,
					productId: data.productId,
					productModel: data.productModel,
					productProperty: data.productProperty,
					battery: '',
					stockStatus: 1,
					stockReserveAccount: data.stockReserveAccount,
					counter: '',
					productSecret: data.productSecret
				}
				if (Property.battery) {
					obj.battery = Property.battery
				}
				if (Property.counter) {
					obj.counter = Property.counter
				} else {
					obj.counter = 30000
				}
				await addDevice(obj);
				await this.setStoreNum(data);
				this.putDisabled = false
			},

			async setStoreNum(data) {
				let modelRes = await getDevModel(data.productModel)
				let deviceType = {
					productModel: data.productModel,
					tenantable: parseInt(modelRes.data[0].tenantable || 0) + 1,
					inStore: parseInt(modelRes.data[0].inStore || 0) + 1,
				}
				console.log(deviceType);
				let res = await addDeviceType(deviceType) //修改品类的在库和可租的数量
				console.log(res);
				// 更新产品推荐的 设备 和可租的数量
				this.$emit('updateDeviceType')
			},
			async leaStore() {

				this.putDisabled = true
				let dRes = await getPidInStore(this.BLEObj.productId);

				if (dRes.data.length > 0) {
					console.log(dRes);
					uni.showToast({
						title: 'Has been bound by the agent, do not repeat storage',
						icon: 'none'
					})
					this.putDisabled = false
					return false
				}
				stockIn({
					productId: this.BLEObj.productId + ''
				}).then(res => {
					console.log(res);
					if (res.code == 0) {
						this.BLEObj = {}
						uni.showToast({
							title: 'Receiving Success',
							icon: 'none'
						});
						// 入库成功之后，本地新增可租赁列表
						this.addDeviceDB(res.data)


					} else {
						this.putDisabled = false
						uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					}
				})
			},



		},
		mounted() {
			this.ble.init();
		},
	}
</script>

<style lang="scss" scoped>
	.putStorage {
		padding: 16px;
		box-sizing: border-box;
		height: 100%;
		
		.popupBox {
			width: 300px;
			min-height: 201px;
			background-color: var(--moduleColor);
			border-radius: 16px;
			position: relative;
			padding: 16px;
			box-sizing: border-box;
		}
		
		.title {
			width: 100%;
			height: 44px;
			line-height: 44px;
			text-align: center;
			color: var(--subjectTextColor);
			font-weight: $uni-fw-700;
			font-size: $uni-fz-17;
		}
		
		.content {
			width: 100%;
			height: 44px;
			line-height: 21px;
			text-align: center;
			background: white;
			color: var(--subjectTextColor);
			font-weight: 400px;
			font-size: 14px;
		}
		
		.center {
		
			width: 100%;
			min-height: 40px;
			overflow: auto;
			margin: 16px 0;
			line-height: 21px;
		
			.textInfo {
				text-align: center;
				font-size: 14px;
				color: var(--subjectTextColor);
				line-height: 21px;
				font-weight: 400;
				margin-bottom: 16px;
				.checkSucc{
					color: #00ffff;
				}
			}
		
			.input_view {
				position: relative;
				border-bottom: 1px solid var(--borderColor) !important;
				height: 41px !important;
				padding-top: 8px;
				box-sizing: border-box;
		
			}
		
		
		
		}
		
		.handleBtn {
			display: flex;
			align-items: center;
			justify-content: space-around;
		
			.cancelText {
				color: var(--subjectColor);
				font-size: 17px;
			}
		
			.confirmText {
				color: $uni-color-white;
				font-size: 17px;
			}
		
			/deep/ button {
				width: 130px;
			}
		}
		
		.reported {
			width: 100%;
			height: 240px;
			border: 1px solid #ccc;
			background-color: #fff;
			padding: 16px;
			box-sizing: border-box;
			overflow-y: auto;

			.flex_box {
				width: 100%;
				height: 240px;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: space-evenly;
			}

			.emptyTips {
				display: flex;
				align-items: center;
				justify-content: space-evenly;
			}

			.storageList {
				width: 100%;
				margin-bottom: 4px;
				font-size: 14px;

				.actionLine {
					color: #2979ff;
				}

				.applyBox {
					width: 120px;

				}
			}
		}

		.record {
			width: 100%;
			height: calc(100% - 250px);
			overflow-y: auto;
			border: 1px solid #ccc;
			background-color: #fff;
			padding: 16px;
			box-sizing: border-box;
			overflow-y: auto;
			margin-top: 8px;

			.recordTitle {
				font-weight: 600;
				display: flex;
				align-items: center;
				justify-content: space-evenly;
			}

			.productid {
				text-align: left;
				width: 120px;
			}

			.productModel {
				text-align: center;
				width: 100px;
			}

			.audio {
				text-align: right;
				width: 40px;
			}

			.recordList {
				margin-top: 8px;
				display: flex;
				align-items: center;
				justify-content: space-evenly;
			}
		}
	}
</style>